package com.clei.Y2020.M07.D23;

import com.clei.utils.PrintUtil;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 好久没写socket程序了，试一哈
 *
 * @author KIyA
 */
public class TCPSocketClient {

    public static void main(String[] args) throws Exception {

        Socket socket = new Socket("127.0.0.1", 8001);
        // 确认连接成功
        byte[] buffer = new byte[1024];
        int length = socket.getInputStream().read(buffer);
        String content = new String(buffer, 0, length, StandardCharsets.UTF_8);
        if (!"connect".equals(content)) {
            return;
        }

        // 写入
        OutputStream os = socket.getOutputStream();
        InputStream is = socket.getInputStream();

        Scanner input = new Scanner(System.in);
        String str;
        while (null != (str = input.nextLine())) {
            os.write(str.getBytes(StandardCharsets.UTF_8));

            // 读取
            length = is.read(buffer);
            content = new String(buffer, 0, length, StandardCharsets.UTF_8);
            PrintUtil.log(content);

            if ("EXIT".equalsIgnoreCase(content)) {
                break;
            }
        }
        is.close();
        os.close();
        socket.close();
    }
}
